//
//  DAUMonDetailVC.m
//  DAU-iOS
//
//  Created by XiangDongMBP on 2016/11/18.
//  Copyright © 2016年 East. All rights reserved.
//

#import "DAUMonDetailVC.h"
#import "DAUMonHumitureTVC.h"
#import "DAUMonitorWarningTVC.h"
#import "DAUMonElectricityVC.h"
#import "DAUMonitorControlTVC.h"
#import <Masonry.h>
#import "XDEmptyVCView.h"

@interface DAUMonDetailVC ()<UIPageViewControllerDelegate, UIPageViewControllerDataSource, XDEmptyVCViewDelegate>

@property (strong, nonatomic) UIPageViewController *pageVC;
@property (strong, nonatomic) NSArray<UIViewController *> *vcArray;
@property (strong, nonatomic) NSArray<UIButton *> *btnArray;
@property (strong, nonatomic) NSArray<UIImageView *> *imgViewArray;
@property (assign, nonatomic) NSInteger index;

@property (weak, nonatomic) IBOutlet UIButton *humitureBtn;
@property (weak, nonatomic) IBOutlet UIImageView *humitureImgView;
@property (weak, nonatomic) IBOutlet UIButton *warningBtn;
@property (weak, nonatomic) IBOutlet UIImageView *warningImgView;
@property (weak, nonatomic) IBOutlet UIButton *elecBtn;
@property (weak, nonatomic) IBOutlet UIImageView *elecImgView;
@property (weak, nonatomic) IBOutlet UIButton *controlBtn;
@property (weak, nonatomic) IBOutlet UIImageView *controlImgView;

@property (strong, nonatomic) UIActivityIndicatorView *indicatiorView;
@property (strong, nonatomic) UIBarButtonItem *indicatiorItem;
@property (strong, nonatomic) UIBarButtonItem *refreshItem;

@property (nonatomic, strong) XDEmptyVCView *emptyView;

@end

@implementation DAUMonDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavigationBar];
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initNavigationBar {
    self.navigationItem.title = self.collectorName;
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"monitor_refresh"] style:UIBarButtonItemStylePlain target:self action:@selector(refreshBtnTapped:)];
    self.refreshItem = rightBarItem;
    
    self.indicatiorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    self.indicatiorItem = [[UIBarButtonItem alloc] initWithCustomView:self.indicatiorView];
    
    self.navigationItem.rightBarButtonItem = self.refreshItem;
}

- (void)initSubViews {
    [self addPageVC];
    
    self.emptyView = [[[NSBundle mainBundle] loadNibNamed:@"XDEmptyVCView" owner:self options:nil] firstObject];
    self.emptyView.delegate = self;
    
    [self requestCollector:self.collectorId];
}

- (void)addPageVC {
    [self.humitureBtn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.warningBtn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.elecBtn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.controlBtn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    DAUMonHumitureTVC * vc1 = [[DAUMonHumitureTVC alloc] init];
    DAUMonitorWarningTVC * vc2 = [[DAUMonitorWarningTVC alloc] init];
    DAUMonElectricityVC * vc3 = [[DAUMonElectricityVC alloc] init];
    DAUMonitorControlTVC * vc4 = [[DAUMonitorControlTVC alloc] init];
    
    self.vcArray = @[vc1, vc2, vc3, vc4];
    self.btnArray = @[self.humitureBtn, self.warningBtn, self.elecBtn, self.controlBtn];
    self.imgViewArray = @[self.humitureImgView, self.warningImgView, self.elecImgView, self.controlImgView];
    
    self.pageVC = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    self.pageVC.delegate = self;
    self.pageVC.dataSource = self;
    [self.pageVC setViewControllers:@[vc1] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    //    self.authDetailBtn.selected = YES;
    
    [self addChildViewController:self.pageVC];
    [self.view addSubview:self.pageVC.view];
    [self.pageVC didMoveToParentViewController:self];
    
    // 添加布局约束
    //    UIView * superView = self.view;
    [self.pageVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(100);
        make.leading.equalTo(self.view.mas_leading).with.offset(0);
        make.bottom.equalTo(self.view.mas_bottom).with.offset(0);
        make.trailing.equalTo(self.view.mas_trailing).with.offset(0);
        //        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(64, 100, 0, -100));
    }];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

#pragma mark - 按键处理
- (void)refreshBtnTapped:(UIBarButtonItem *)item {
    [self requestCollector:self.collectorId];
}

- (void)btnTapped:(UIButton *)btn {
    self.index = [self.btnArray indexOfObject:btn];
    [self selectBtnAtIndex:self.index];
    
    UIViewController *vc = self.vcArray[self.index];
    [self.pageVC setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
}

#pragma mark - 私有函数
- (void)selectBtnAtIndex:(NSInteger)index {
    [self.imgViewArray enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.hidden = (index != idx);
    }];
}

- (void)startRefreshAnimation:(BOOL)isRefresh {
    if (isRefresh) {
        self.navigationItem.rightBarButtonItem = self.indicatiorItem;
        [self.indicatiorView startAnimating];
    } else {
        [self.indicatiorView setHidden:YES];
        self.navigationItem.rightBarButtonItem = self.refreshItem;
    }
}

- (void)refreshWholeView {
    // 这里是默认了一个类型，只是为了可以调用刷新函数
    DAUMonHumitureTVC *vc = (DAUMonHumitureTVC *)self.vcArray[self.index];
    [vc refreshWholeView];
}

#pragma mark - <UIPageViewControllerDelegate>代理
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    UIViewController * vc = [pendingViewControllers firstObject];
    self.index = [self.vcArray indexOfObject:vc];
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        [self selectBtnAtIndex:self.index];
    }
}

#pragma mark - <UIPageViewControllerDataSource>代理
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSUInteger index = [self.vcArray indexOfObject:viewController];
    NSLog(@"before %zd", index);
    if (index > 0) {
        return self.vcArray[index - 1];
    }
    return nil;
}
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    NSUInteger index = [self.vcArray indexOfObject:viewController];
    NSLog(@"after %zd", index);
    if (index < self.vcArray.count - 1) {
        return self.vcArray[index + 1];
    }
    return nil;
}

#pragma mark - <XDEmptyVCViewDelegate>代理
- (void)xDEmptyVCView:(XDEmptyVCView *)selPhotoView refreshBtnTapped:(UIButton *)btn {
    [self requestCollector:self.collectorId];
}

#pragma mark - 网络请求
- (void)requestCollector:(NSInteger)collectorId {
    [self startRefreshAnimation:YES];
    
    NSString *urlStr = [DAUUrlProtocolMerger apiCollector];
    NSDictionary *pars = @{@"id" : @(self.collectorId)};
    
    [XDAFHttpRequest GET:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self startRefreshAnimation:NO];
        NSLog(@"请求采集器返回 %@", responseObject);
        if ([responseObject[@"errCode"] integerValue] == 200) {
            DAUEngineDetailModel *temp = [DAUEngineDetailModel yy_modelWithJSON:responseObject];
            DAU_APP_DELEGATE.dauModel.engineDetail = temp;
            [self.emptyView hide];
            [self refreshWholeView];
        } else {
            [self.emptyView showInView:self.view];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"msg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self startRefreshAnimation:NO];
        NSLog(@"请求采集器失败 %@", error);
        [self.emptyView showInView:self.view];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:NSLocalizedString(@"网络请求失败", nil)];
    }];
}

@end
